<?php

namespace App\Http\Services;

use App\Http\Model\Api\FinanceDiamondStream;
use App\Http\Model\AudioApi;
use App\Http\Model\Call;
use App\Http\Model\Config;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\Medal;
use App\Http\Model\Task;
use App\Http\Model\User;
use App\Lib\Publisher;

class TaskServices extends CommonServices
{
    private $taskModel;
    private $audioModel;
    private $userModel;
    private $configModel;
    private $giftModel;
    private $medalModel;
    private $streamModel;
    private $call = 247;//打call
    private $medal_id = 89;//勋章id
    private $redisLook = 'AWARD:USER:';
    private $diamondPond_1 = 500000;//钻石瓜分池 $num<=50人
    private $diamondPond_2 = 1000000;//钻石瓜分池 51 <= $num <=200人
    private $diamondPond_3 = 3000000;//钻石瓜分池 201<= $num <= 1000
    private $diamondPond_4 = 5000000;//钻石瓜分池 $num > 1000
    private $taskMsg = ['使用火箭一次', '关注20名好友', '赠送20次打call', '成功发送一条动态', '开启一次小屋', '赠送任意钻石礼物', '充值1元', '不同厅上麦10次', '神秘邂逅成功一次', '参与一次砸蛋'];

    public function __construct()
    {
        $this->taskModel = new  Task();
        $this->audioModel = new  AudioApi();
        $this->userModel = new  User();
        $this->configModel = new  Config();
        $this->giftModel = new  Gift();
        $this->medalModel = new  Medal();
        $this->streamModel = new  FinanceDiamondStream();
    }

    //获取用户活动基本信息
    public function getTaskInfo($user_id)
    {
        $code = 0;
        $msg = '成功';
        $data = [];
        do {
            //获取用户信息
            $data['user_info'] = $this->userModel->getUserInfoToCache($user_id);
            //任务完成次数
            $complete = $this->taskModel->getTaskCompleteNum($user_id);
            $data['complete'] = $complete > 15 ? 15 : $complete;
            //获取超级任务
            $data['superTask'] = '';
            $superTask = $this->taskModel->getSuperUserTask($user_id) ?? '';
            if ($superTask) {
                $superTask = json_decode($superTask, true);
                $data['superTask'] = $superTask[count($superTask) - 1];
                //获取任务完成次数
                $data['superTask']['superTaskNum'] = $this->getTaskNum($user_id, $data['superTask']['task_id'], $data['superTask']['timestamp'], $data['superTask']['status']);
            }
            //免费任务
            $data['freeTask'] = '';
            $freeTask = $this->taskModel->getUserFreeTask($user_id) ?? '';
            if ($freeTask) {
                $data['freeTask'] = json_decode($freeTask, true);
            }

            $data['refreshNum'] = $this->taskModel->getUserRefreshNum($user_id);//刷新次数

            $data['awardDiamond'] = [
                'diamond' => 0,//可领取钻石数量
                'click' => 0,//是否可点击
                'is_award' => 0,//是否可领取
            ]; // 用户瓜分相关信息
            $awardDate = $this->configModel->getConfigDate('31', 'task_award_date');
            $awardDate = explode(' - ', $awardDate);
            $startAwardDate = strtotime($awardDate[0]);
            $endAwardDate = strtotime($awardDate[1]);
            //判断当前时间是否可瓜分
            if (time() >= $startAwardDate and time() <= $endAwardDate) {
                $click = 0;//是否可点击
                $is_award = 0;//是否可领取
                if ($complete >= 15) {
                    $is_award = 1;//可领取
                }
                //查看用户是否领取
                $log = $this->taskModel->getAwardLog($user_id);
                if (!$log and $complete >= 15) { //未领取过钻石
                    $click = 1; //可点击
                }
                $diamond = $this->computeDiamond($user_id);//可领取钻石数量
                $data['awardDiamond'] = compact('diamond', 'click', 'is_award');
            }

            //活动时间
            $data['date'] = '2021-03-26 - 2021-03-31';
        } while (false);
        return compact('code', 'msg', 'data');
    }

    //点击领取钻石
    public function clickAwardDiamond($user_id)
    {
        $code = 0;
        $msg = '瓜分成功';
        $data = [];
        do {
            $awardDate = $this->configModel->getConfigDate('31', 'task_award_date');
            $awardDate = explode(' - ', $awardDate);
            $startAwardDate = strtotime($awardDate[0]);
            $endAwardDate = strtotime($awardDate[1]);

            //判断当前时间是否可瓜分
            if (time() <= $startAwardDate or time() >= $endAwardDate) {
                $code = 3001;
                $msg = '亲~3月31日0点整瓜分，请耐心等待~';
                break;
            }
            //查看用户是否领取
            $log = $this->taskModel->getAwardLog($user_id);
            if ($log) { //领取过钻石
                $code = 0;
                $msg = '您已领取过所瓜分的钻石~';
                $data['diamond'] = $log;
                break;
            }
            //获取领取钻石
            $diamond = $this->computeDiamond($user_id);//可领取钻石数量
            if ($diamond <= 0) {
                $code = 3001;
                $msg = '瓜分钻石数量错误~';
                break;
            }
            //记录领取缓存
            $res = $this->taskModel->setAwardLog($user_id, $diamond);
            if ($res == 0) {
                $code = 3001;
                $msg = '领取失败~';
                break;
            }
            $stream = $this->streamModel->getTaskCompactDiamond($user_id, $startAwardDate, $endAwardDate);
            if ($stream) {
                $code = 3001;
                $msg = '领取失败~您已参与瓜分';
                break;
            }
            $this->audioModel->diamond_recharge($user_id, $diamond, 10);//瓜分钻石赠送钻石
            $data['diamond'] = $diamond;
            $apiMsg = '恭喜您在瓜分500万活动中，瓜分到了' . $diamond . '钻石，钻石已经发送到您的账户内，请查看钱包明细';
            $this->audioModel->sendMsgApi($user_id, $apiMsg);
        } while (false);
        return compact('code', 'msg', 'data');

    }

    public function refreshTask($user_id)
    {
        $code = 0;
        $msg = '成功';
        $data = [];
        do {
            //校验任务
            $this->completeSuperTask($user_id);
            //查看今日超级任务是否完成
            $superTask = $this->taskModel->getSuperUserTask($user_id) ?? '';
//            if ($superTask && time() < 1617033600) { //最后一天可无限刷新 完成
//                $superTask = json_decode($superTask, true);
//                $task = $superTask[count($superTask) - 1];
//                if ($task['status'] == 1) {
//                    $code = 3001;
//                    $msg = '您今日超级任务已完成';
//                    break;
//                }
//            }
            //查看用户今日刷新次数
            $refreshNum = $this->taskModel->getUserRefreshNum($user_id);
            if ($refreshNum < 2) {
                //免费机会
                $this->taskModel->refreshTaskNum($user_id);
                $this->refreshTaskCache($user_id);
                break;
            }
            if (time() < 1617033600 and $refreshNum >= 4) { //1615564800
                //付费
                $code = 3001;
                $msg = '您的付费加速到达当日上限~';
                break;
            }
            $pay_res = $this->audioModel->diamond_recharge($user_id, 100, 9);
            if ($pay_res['code'] != 0) {
                $code = $pay_res['code'];
                $msg = $pay_res['msg'];
                break;
            }
            $this->taskModel->refreshTaskNum($user_id);
            $this->refreshTaskCache($user_id);
        } while (false);
        return compact('code', 'msg', 'data');
    }


    //免费任务完成情况
    public function completeFreeTask($user_id)
    {
        $code = 0;
        $msg = '成功';
        $data = [];
        do {
            $date = $this->configModel->getConfigDate('30', 'task_date');
            //首次登陆
            $freeTask = $this->taskModel->getUserFreeTask($user_id);
            if (!$freeTask) {
                //免费任务完成情况
                $data[0] = ['free_id' => 0, 'status' => 1, 'task_msg' => '登录一次'];
                //新增次数
                $this->incCompleteNum($user_id);
                //查询是否有实名认证用户
                $res = $this->userModel->checkInviteUser($user_id, $date);
                $status = empty($res) ? 0 : 1;
                $data[1] = ['free_id' => 1, 'status' => $status, 'task_msg' => '邀请并实名认证一名用户'];
                $this->taskModel->setUserFreeTask($user_id, json_encode($data));
                if ($status == 1) {
                    //新增次数
                    $this->incCompleteNum($user_id);
                }
                break;
            }
            $freeTask = json_decode($freeTask, true);
            $invite = $freeTask[1];
            if ($invite['status'] == 1) {
                break;
            }
            $res = $this->userModel->checkInviteUser($user_id, $date);
            $status = empty($res) ? 0 : 1;
            $freeTask[1] = ['free_id' => 1, 'status' => $status, 'task_msg' => '邀请并实名认证一名用户'];
            $this->taskModel->setUserFreeTask($user_id, json_encode($freeTask));
            if ($status == 1) {
                //新增次数
                $this->incCompleteNum($user_id);
            }
        } while (false);
        return compact('code', 'msg', 'data');

    }


    public function getSuperUserList()
    {
        $freeTask = $this->taskModel->getFreeTaskUser();
        $freeTask = array_keys($freeTask);
        $superTask = $this->taskModel->getAllSuperTaskUser();
        $superTask = array_keys($superTask);
        $data = array_unique(array_merge($freeTask, $superTask));
        foreach ($data as $v) {
            if (intval($v) == 0) continue;
            $this->completeFreeTask($v);
            $this->completeSuperTask($v);
        }
    }

    //超级任务
    public function completeSuperTask($user_id)
    {
        do {
            $lookKey = $this->redisLook . $user_id;
            if (redis_lock($lookKey, 10) == false) {
                //校验任务
                break;
            }
            //获取用户超级任务
            $superTask = $this->taskModel->getSuperUserTask($user_id) ?? '';
            if (!$superTask) {
                break;
            }
            $superTask = json_decode($superTask, true);
            $task = $superTask[count($superTask) - 1];
            if ($task['status'] == 1) {
                break;
            }
            $task_id = $task['task_id'];
            $timestamp = $task['timestamp'];
            $status = 0;
            switch ($task_id) {
                case 0://使用火箭一次
                    $rocket = $this->taskModel->getRocket($timestamp);
                    if (in_array($user_id, $rocket)) {
                        $status = 1;
                    }
                    break;
                case 1://关注20名好友
                    $follow = $this->userModel->followUser($user_id, $timestamp);
                    if (count($follow) >= 20) {
                        $status = 1;
                    }
                    break;
                case 2://赠送20次打call
                    $giftNum = $this->giftModel->getGiftStreamNum($user_id, [$this->call], $timestamp);
                    if ($giftNum >= 20) {
                        $status = 1;
                    }
                    break;
                case 3://成功发送一条动态
                    $trends = $this->userModel->getUserTrendsContent($user_id, $timestamp);
                    if ($trends) {
                        $status = 1;
                    }
                    break;
                case 4://开启一次小屋
                    $openRoom = $this->taskModel->getOpenRoom($user_id);
                    if ($openRoom) {
                        $roomTime = explode('_', $openRoom);
                        if ($timestamp < $roomTime[1]) {
                            $status = 1;
                        }
                    }
                    break;
                case 5://赠送任意钻石礼物
                    $giftNum = $this->giftModel->getGiftStreamCount($user_id, $timestamp, 1);
                    if (count($giftNum) >= 1) {
                        $status = 1;
                    }
                    break;
                case 6://充值1元
                    $recharge = $this->userModel->getUserRechargeOrder($user_id, $timestamp);
                    if ($recharge) {
                        $status = 1;
                    }
                    break;
                case 7://不同房间上麦10次
                    $joinNum = $this->taskModel->getJoinRoom($user_id);
                    if (!$joinNum) {
                        break;
                    }
                    $num = 0;
                    $joinNum = json_decode($joinNum, true);
                    foreach ($joinNum as $v) {
                        if ($v['timestamp'] > $timestamp) {
                            $num++;
                        }
                    }
                    if ($num >= 10) {
                        $status = 1;
                    }
                    break;
                case 8://神秘邂逅成功一次
                    $meet = $this->taskModel->getMeet($user_id);
                    if ($timestamp < $meet) {
                        $status = 1;
                    }
                    break;
                case 9://参与一次砸蛋
                    $hammer = $this->userModel->getUserHammerLog($user_id, $timestamp);
                    if (abs($hammer) > 0) {
                        $status = 1;
                    }
                    break;
            }
            $task['status'] = $status;
            $superTask[count($superTask) - 1] = $task;
            $this->taskModel->refreshSuperUserTask($user_id, json_encode($superTask));
            if ($status == 1) {
                //新增次数
                $this->incCompleteNum($user_id);
            }
            redis_unlock($lookKey);

        } while (false);
    }


    //获取任务完成次数
    public function getTaskNum($user_id, $task_id, $timestamp, $status)
    {
        $num = 0;
        $allNum = 1;
        switch ($task_id) {
            case 0://使用火箭一次
                $rocket = $this->taskModel->getRocket($timestamp);
                if (in_array($user_id, $rocket)) {
                    $num = 1;
                }
                break;
            case 1://关注20名好友
                $num = $this->userModel->followUser($user_id, $timestamp);
                $allNum = 20;
                $num = count($num) >= 20 ? 20 : count($num);
                if ($status == 1) $num = 20;
                break;
            case 2://赠送20次打call
                $allNum = 20;
                $num = $this->giftModel->getGiftStreamNum($user_id, [$this->call], $timestamp);
                $num = $num >= 20 ? 20 : $num;
                break;
            case 3://成功发送一条动态
                $trends = $this->userModel->getUserTrendsContent($user_id, $timestamp);
                if ($trends) {
                    $num = 1;
                }
                if ($status == 1) $num = 1;
                break;
            case 4://开启一次小屋
                $openRoom = $this->taskModel->getOpenRoom($user_id);
                if ($openRoom) {
                    $roomTime = explode('_', $openRoom);
                    if ($timestamp < $roomTime[1]) {
                        $num = 1;
                    }
                }
                break;
            case 5://赠送任意钻石礼物
                $giftNum = $this->giftModel->getGiftStreamCount($user_id, $timestamp, 1);
                if (count($giftNum) >= 1) {
                    $num = 1;
                }
                break;
            case 6://充值1元
                $recharge = $this->userModel->getUserRechargeOrder($user_id, $timestamp);
                if ($recharge) {
                    $num = 1;
                }
                break;
            case 7://任意厅上麦10次
                $allNum = 10;
                $joinNum = $this->taskModel->getJoinRoom($user_id);
                if (!$joinNum) {
                    break;
                }
                $joinNum = json_decode($joinNum, true);
                foreach ($joinNum as $v) {
                    if ($v['timestamp'] > $timestamp) {
                        $num++;
                    }
                }
                $num = $num >= 10 ? 10 : $num;
                break;
            case 8://神秘邂逅成功一次
                $meet = $this->taskModel->getMeet($user_id);
                if ($timestamp < $meet) {
                    $num = 1;
                }
                break;
            case 9://参与一次砸蛋
                $hammer = $this->userModel->getUserHammerLog($user_id, $timestamp);
                if (abs($hammer) > 0) {
                    $num = 1;
                }
                break;
        }
        $res = $num . '/' . $allNum;
        return $res;
    }


    //用户完成次数+1
    public function incCompleteNum($user_id)
    {
        do {
            $this->taskModel->setTaskCompleteNum($user_id);
            $completeNum = $this->taskModel->getTaskCompleteNum($user_id);
            if ($completeNum >= 15) {
                //完成15次
                $medal = $this->medalModel->getUserMedal($user_id, $this->medal_id);
                if (!$medal) {
                    //未发放勋章
                    $msg = '恭喜您完成瓜分活动中的所有任务，特送您专属勋章-声撩投资家（30天），奖励已发放请您注意查收';
                    $this->audioModel->sendMsgApi($user_id, $msg);
                    $this->audioModel->sendMedal($user_id, $this->medal_id, 30);
                }
                $this->taskModel->setEnergyNumber($user_id);
            }
        } while (false);
        return true;
    }

    //新增任务缓存
    public function refreshTaskCache($user_id)
    {
        do {
            $taskId = $this->taskModel->popPond();

            if ($taskId === null) {
                $this->taskModel->createPond();
                $taskId = $this->taskModel->popPond();
            }
            $data = ['task_id' => $taskId, 'status' => 0, 'taskMsg' => $this->taskMsg[$taskId], 'timestamp' => time()];//任务id
            $userTask = $this->taskModel->getSuperUserTask($user_id);
            $userTask = json_decode($userTask, true) ?? [];
            $userTask[count($userTask)] = $data;
            $val = json_encode($userTask);
            $this->taskModel->refreshSuperUserTask($user_id, $val);
        } while (false);
        return true;
    }

    //计算用户可获得钻石
    public function computeDiamond($user_id)
    {
        do {
            $diamond = 0;
            $complete = $this->taskModel->getTaskCompleteNum($user_id);
            if ($complete < 15) {
                break;
            }
            //获取达标用户赋能值
            $completeUser = $this->taskModel->getEnergyNumber();
            //达标用户数量
            $countNum = count($completeUser);
            //默认为不足50人奖金池子
            $diamondPond = $this->diamondPond_1;
            //用户赋能值
            $userEnergyNum = $completeUser[$user_id] ?? 0;
            //所有用户赋能值总和
            $allEnergyNum = $userEnergySum = array_sum($completeUser);
            if ($countNum <= 50) {
                //补齐用户池子
                $allEnergyNum = (50 - $countNum) * 5 + $userEnergySum;
            } else if ($countNum >= 51 and $countNum <= 200) {
                $diamondPond = $this->diamondPond_2;//50-200
            } else if ($countNum >= 201 and $countNum <= 1000) {
                $diamondPond = $this->diamondPond_3;//200-1000人奖金池子
            } else if ($countNum > 1001) {
                $diamondPond = $this->diamondPond_4;//>1000人奖金池子
            }
            $diamond = intval($userEnergyNum / $allEnergyNum * $diamondPond);//
        } while (false);
        return $diamond;
    }

    //用户邀请
    public function getInvite($user_id)
    {
        $code = 0;
        $msg = '成功';
        $data = [];
        do {
            $data['user_info'] = $this->userModel->getUserInfoToCache($user_id);
            $date = $this->configModel->getConfigDate('30', 'task_date');
            $res = $this->userModel->checkInviteUserList($user_id, $date);
            $data['invite_num'] = count($res);
        } while (false);
        return compact('code', 'msg', 'data');
    }

    public function test($countNum)
    {
        $k = time();
        for ($i = 0; $i < $countNum; $i++) {
            $this->taskModel->setEnergyNumberTest($i, $k);
        }
        $sumDiamond = 0;
        for ($user_id = 0; $user_id < $countNum; $user_id++) {
            //获取达标用户赋能值
            $completeUser = $this->taskModel->getEnergyNumberTest(0, $k);
            //达标用户数量
            $countNum = count($completeUser);
            //默认为不足50人奖金池子
            $diamondPond = $this->diamondPond_1;
            //用户赋能值
            $userEnergyNum = $completeUser[$user_id] ?? 0;
            //所有用户赋能值总和
            $allEnergyNum = $userEnergySum = array_sum($completeUser);
            if ($countNum <= 50) {
                //补齐用户池子
                $allEnergyNum = (50 - $countNum) * 5 + $userEnergySum;
            } else if ($countNum >= 51 and $countNum <= 200) {
                $diamondPond = $this->diamondPond_2;//50-200
            } else if ($countNum >= 201 and $countNum <= 1000) {
                $diamondPond = $this->diamondPond_3;//200-1000人奖金池子
            } else if ($countNum > 1001) {
                $diamondPond = $this->diamondPond_4;//>1000人奖金池子
            }
            $d = intval($userEnergyNum / $allEnergyNum * $diamondPond);
            $sumDiamond = $d + $sumDiamond;
            $diamond[$i][] = ['userEnergyNum' => $userEnergyNum, 'diamond' => $d];
        }
        echo '人数区间总钻石' . $diamondPond;
        echo '<br>';
        echo '总发放钻石' . $sumDiamond;
        dd($diamond);
    }
}
